#include "responsehandlerthreadpool.h"
#include "responsehandlerthread.h"

ResponseHandlerThreadPool *ResponseHandlerThreadPool::m_instance=0;

QMutex ResponseHandlerThreadPool::m_mutex;

ResponseHandlerThreadPool::ResponseHandlerThreadPool()
{
    if(m_runningThreadList == NULL)
    {

        m_runningThreadList = new QList<ResponseHandlerThread*>();
    }

    purgeStopThread();
}

ResponseHandlerThreadPool::~ResponseHandlerThreadPool()
{

    int i = 0;
    if(m_runningThreadList != NULL)
    {
        if(!m_runningThreadList->isEmpty())
        {
            for(i = 0; i<m_runningThreadList->size(); ++i)
            {
                delete m_runningThreadList->at(i);
            }

            m_runningThreadList->clear();

        }
    }
    if(m_purgeThread != NULL)
    {
        m_purgeThread->setStop(true);
        delete m_purgeThread;
    }


}

void ResponseHandlerThreadPool::purgeStopThread()
{
    m_purgeThread = new PurgeHandlerThread();
    m_purgeThread->start();
}

int ResponseHandlerThreadPool::addHandlerThread(ResponseHandlerThread* thread)
{
    QMutexLocker locker(&m_mutex);

    if((m_runningThreadList == NULL) || (thread == NULL) )
    {
        return -1;
    }

    m_runningThreadList->push_back(thread);

}

int ResponseHandlerThreadPool::removeHandlerThread(ResponseHandlerThread* thread)
{
    QMutexLocker locker(&m_mutex);

    if((m_runningThreadList == NULL) || (thread == NULL) )
    {
        return -1;
    }

    m_runningThreadList->removeOne(thread);
    delete thread;
}

ResponseHandlerThread *ResponseHandlerThreadPool::getHandlerThread(unsigned int request_id)
{
    if((m_runningThreadList != NULL) && (m_runningThreadList->isEmpty()))
    {
        for(int i = 0; i < m_runningThreadList->size(); ++i)
        {
            if(request_id == m_runningThreadList->at(i)->getRequestID())
            {
                return m_runningThreadList->at(i);
            }
        }
    }

    return NULL;
}

PurgeHandlerThread::PurgeHandlerThread()
{
    m_stop = true;
}

PurgeHandlerThread::~PurgeHandlerThread()
{
    m_stop = false;
}

void PurgeHandlerThread::run()
{
    QList<ResponseHandlerThread*> *list;
    int i = 0;
    while(m_stop)
    {
        list = ResponseHandlerThreadPool::getInstance()->getThreadList();
        for(i = 0; i < list->size(); ++i)
        {
            if(list->at(i)->isFinished())
            {
                ResponseHandlerThreadPool::getInstance()->removeHandlerThread(list->at(i));
            }
        }

        QThread::sleep(5);
    }


}
